﻿using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using Neo4JConnector.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Neo4JConnector
{
    [Icon("pack://application:,,,/Neo4JConnector;component/Resources/Icon.png")]
    [Category("neo4j图数据库")]
    [OrderWeight(111)]
    public class ClearNodes : BaseNeo4JOp
    {

        [FormulaProperty]
        [DisplayName("节点的标签")]
        [Description("类似于数据库中的表，用于对节点进行分类。")]
        [OrderWeight(100)]
        [SearchableProperty]
        public object LabelExpr { get; set; }


        [DisplayName("将删除的节点数量保存到变量")]
        [OrderWeight(999)]
        [ResultToProperty]
        public string ResultInParamater { get; set; } = "RemovedNodeCount";


        public override async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var label = (await dataContext.EvaluateFormulaAsync(LabelExpr))?.ToString() ?? "";

            if (string.IsNullOrEmpty(label))
            {
                throw new Exception("被删除节点的标签不能为空。");
            }

            if (!Validators.IsValidLabel(label))
                throw new Exception("节点的标签包含非法字符，仅支持字母数字和下划线，且需要以字母开头。");

            var client = await getClient(dataContext);

            var idList = await client.GetAllEntities(label);

            foreach (string id in idList)
            {
                await client.DeleteEntity(label, id);
            }

            if (!string.IsNullOrEmpty(ResultInParamater))
            {
                dataContext.Parameters[ResultInParamater] = idList.Count;
            }

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "neo4j：删除全部节点";
        }
    }
}
